using System;
using BCrypt.Net;

namespace JGSY.CourseManagement.Infrastructure.Security
{
    /// <summary>
    /// 使用BCrypt算法的密码哈希服务
    /// </summary>
    public interface IPasswordHasher
    {
        /// <summary>
        /// 对密码进行哈希处理
        /// </summary>
        /// <param name="password">明文密码</param>
        /// <returns>哈希后的密码</returns>
        string HashPassword(string password);

        /// <summary>
        /// 验证密码是否匹配哈希值
        /// </summary>
        /// <param name="password">明文密码</param>
        /// <param name="hash">存储的哈希值</param>
        /// <returns>是否匹配</returns>
        bool VerifyPassword(string password, string hash);
    }

    /// <summary>
    /// BCrypt密码哈希实现
    /// </summary>
    public class BCryptPasswordHasher : IPasswordHasher
    {
        private readonly int _workFactor;

        /// <summary>
        /// 初始化BCrypt密码哈希器
        /// </summary>
        /// <param name="workFactor">工作因子(4-31)，值越高安全性越好但性能消耗越大</param>
        public BCryptPasswordHasher(int workFactor = 12)
        {
            if (workFactor < 4 || workFactor > 31)
                throw new ArgumentOutOfRangeException(nameof(workFactor), "工作因子必须在4-31之间");

            _workFactor = workFactor;
        }

        /// <inheritdoc/>
        public string HashPassword(string password)
        {
            if (string.IsNullOrWhiteSpace(password))
                throw new ArgumentException("密码不能为空", nameof(password));

            return BCrypt.Net.BCrypt.HashPassword(password, _workFactor);
        }

        /// <inheritdoc/>
        public bool VerifyPassword(string password, string hash)
        {
            if (string.IsNullOrWhiteSpace(password))
                return false;
            if (string.IsNullOrWhiteSpace(hash))
                return false;

            return BCrypt.Net.BCrypt.Verify(password, hash);
        }
    }
}
